<?

	require_once('lib/OwnedObject.php');

	define(QUESTION_STATUS_UNANSED, 1);
	define(QUESTION_STATUS_ANSED,   2);

	class Question extends OwnedObject{
			protected $modelName = 'Question';
			protected $status=QUESTION_STATUS_UNANSED;
			protected $content='';
			protected $answer='';


			public static function Install() {
                    OwnedObject::Install();
					$query=sprintf("CREATE TABLE `Question` (
									`Id` INT( 32 ) unsigned NOT NULL ,
									`status` INT( 4 ) NOT NULL ,
									`content` TEXT NOT NULL ,
									`answer` TEXT NOT NULL ,
									PRIMARY KEY ( `Id` ),
									FOREIGN KEY (`Id`) REFERENCES `Object`(`id`) ON DELETE CASCADE
									) ENGINE=INNODB DEFAULT CHARSET=utf8;
								");
					mysql_query($query);

					$query = sprintf("INSERT INTO `ObjectType` SET `name` = '%s'", strval(__CLASS__));
                        mysql_query($query);
					echo "Question installed\n";
			}

			public function Load() {
                        parent::Load();

                        $query = sprintf("SELECT
												`content`, `answer`, `status`
										FROM
											`Question`
										WHERE
											`Id` =%d", $this->id);
                        $res = mysql_query($query);
                        $row = mysql_fetch_array($res);

                        $this->content = $row[0];
                        $this->answer = $row[1];
                        $this->status = $row[2];
			}

			public function AsSource($otherName = 'Question'){
						$result = parent::AsSource($otherName);

						$result -> Attribute('status',$this->status);

						$content = new XmlSource('content',$this->content);
						$answer = new XmlSource('answer',$this->answer);

						$result -> MountSource($content);
						$result -> MountSource($answer);

						return $result;
			}

			public function Content($newContent=false) {
                        if($newContent)
                                $this->content = $newContent;
                        return $this->content;
            }

			public function Answer($newAnswer=false) {
                        if($newAnswer){
                                $this->answer = $newAnswer;
								$this->status = QUESTION_STATUS_ANSED;
						}
                        return $this->answer;
            }

			public function RegisterObject(){
						$obj_id= parent::RegisterObject();
						$query=sprintf("INSERT INTO
												`Question` ( `Id` , `status` , `content` , `answer` )
											VALUES (%d, %d, '%s', '%s')
							", $obj_id, $this->status, mes($this->content), mes($this->answer));
						mysql_query($query);
			}


			public function Save(){
						//если задается вопрос
						if($this->id<1){
							$this->RegisterObject();
						}
						//если на вопрос ответили
						else{
							if($this->answer) $this->status=QUESTION_STATUS_ANSED;
							$query=sprintf("UPDATE `Question`
											SET
												  `status`= %d,
												  `content`= '%s',
												  `answer`= '%s'
											WHERE `Id`=%d", $this->status, mes($this->content), mes($this->answer), $this->id);
							mysql_query($query);
						}
			}


			//забираем  $num отвеченныx вопросов
			public static function FAQ($num=false){
				$query = sprintf("SELECT q.`Id` FROM `Question` q, `Object` o  
				WHERE q.`Id`=o.`id` and `status`=%d ORDER BY o.`created` DESC", QUESTION_STATUS_ANSED);

				if($num){
					$query = sprintf("SELECT `Id`	FROM `Question` WHERE `status`=%d ORDER BY RAND() LIMIT %d", QUESTION_STATUS_ANSED, $num);
				}

				$parse = mysql_query($query);

				$faq = new XmlSource('faq');
				while($result = mysql_fetch_assoc($parse)){
					$q_id = $result['Id'];
					$ques = new Question($q_id);
					$ques->Load();
					$ques_source = $ques->AsSource();


					$author = new User($ques->Owner());
					$author->Load();

					$ques_source->MountSource($author->AsSource('Author'));

					$faq->MountSource($ques_source);
				}

				return $faq;
			}


			//забираем неотвеченные вопросы
			public static function Questions(){
					$query = sprintf("SELECT q.`Id` FROM `Question` q, `Object` o 
					WHERE q.`Id`=o.`id` and q.`status`=%d ORDER BY o.`created` DESC", QUESTION_STATUS_UNANSED);
					$parse = mysql_query($query);

					$faq = new XmlSource('unansed-faq');
					while($result = mysql_fetch_assoc($parse)){
						$q_id = $result['Id'];
						$ques = new Question($q_id);
						$ques->Load();
						$ques_source = $ques->AsSource();

						$author = new User($ques->Owner());
						$author->Load();

						$ques_source->MountSource($author->AsSource('Author'));

						$faq->MountSource($ques_source);
					}

					return $faq;
			}

			//генерируется рыба-вопросов
			// From Technology: Сохраняйте файлы в кодировке UTF-8 епт!
			public static function CreateQuestionFish($ansed, $unansed){
				$ques = array('Как ','Где ','Почем ','Зачем ','Почему ', 'Нафик ');
				$subs = array('чайник ','конь ','собака ','порталл ','погода ','история ','дождь ');
				$verbs = array('мурлычит ','гавкает ','тикает ','ищет ','стоит ','лежит ','прыгает ','ездиет ','ползает');
				$anses = array('Потому что ','Так как ','А ','Вот ','... ');

				$qc = count($ques);
				$sc = count($subs);
				$vc = count($verbs);
				$ac = count($anses);

				for($i=0;$i<$ansed;$i++){
					$q=$ques[rand(0,$qc)].$subs[rand(0,$sc)].$verbs[rand(0,$vc)].'?';
					$a=$anses[rand(0,$ac)].$subs[rand(0,$sc)].$verbs[rand(0,$vc)];

					$question = new Question();
					$question->Content($q);
					$question->Answer($a);
					$question->Save();
				}

				for($i=0;$i<$unansed;$i++){
					$q=$ques[rand(0,$qc)].$subs[rand(0,$sc)].$verbs[rand(0,$vc)].'?';

					$question = new Question();
					$question->Content($q);
					$question->Save();
				}
			}

			public function Remove(){
				$query=sprintf("DELETE FROM `Question` WHERE Id=%d",$this->id);
				mysql_query($query);
				parent::Remove();
			}

	}

?>